import web 
import os
import sys
from web.net import validaddr, validip
from web.utils import listget

from web import httpserver

class RunServer(web.application):

    def run(self, *middleware):
        return self.runwsgi(self.wsgifunc(*middleware))

    def _runwsgi(self,func):
        """
        Runs a WSGI-compatible `func` using FCGI, SCGI, or a simple web server,
        as appropriate based on context and `sys.argv`.
        """
        if os.environ.has_key('SERVER_SOFTWARE'): # cgi
            os.environ['FCGI_FORCE_CGI'] = 'Y'
        
        if (os.environ.has_key('PHP_FCGI_CHILDREN') #lighttpd fastcgi
          or os.environ.has_key('SERVER_SOFTWARE')):
            return runfcgi(func, None)
        
        if 'fcgi' in sys.argv or 'fastcgi' in sys.argv:
            args = sys.argv[1:]
            if 'fastcgi' in args: args.remove('fastcgi')
            elif 'fcgi' in args: args.remove('fcgi')
            if args:
                return runfcgi(func, validaddr(args[0]))
            else:
                return runfcgi(func, None)
        
        if 'scgi' in sys.argv:
            args = sys.argv[1:]
            args.remove('scgi')
            if args:
                return runscgi(func, validaddr(args[0]))
            else:
                return runscgi(func)
        
        return httpserver.runsimple(func, validip(listget(sys.argv, 1, '')))


    def runwsgi(self,func):
        """
        Runs a WSGI-compatible `func` using FCGI, SCGI, or a simple web server,
        as appropriate based on context and `sys.argv`.
        """
         
        if os.environ.has_key('SERVER_SOFTWARE'): # cgi
            os.environ['FCGI_FORCE_CGI'] = 'Y'
     
        if (os.environ.has_key('PHP_FCGI_CHILDREN') #lighttpd fastcgi
          or os.environ.has_key('SERVER_SOFTWARE')):
            return runfcgi(func, None)
         
        if 'fcgi' in sys.argv or 'fastcgi' in sys.argv:
            args = sys.argv[1:]
            if 'fastcgi' in args: args.remove('fastcgi')
            elif 'fcgi' in args: args.remove('fcgi')
            if args:
                return runfcgi(func, validaddr(args[0]))
            else:
                return runfcgi(func, None)
         
        if 'scgi' in sys.argv:
            args = sys.argv[1:]
            args.remove('scgi')
            if args:
                return runscgi(func, validaddr(args[0]))
            else:
                return runscgi(func)
         
         
        server_addr = validip(listget(sys.argv, 2, ''))
        if os.environ.has_key('PORT'): # e.g. Heroku
            server_addr = ('0.0.0.0', intget(os.environ['PORT']))
         
        return httpserver.runsimple(func, server_addr)

